import type { PostType } from '@src/controllers/posts';
import { User } from '@src/db/schema/users';
import { getCategories } from '@src/services/categories';
import { getComments } from '@src/services/comments';
import { getPosts } from '@src/services/posts';
import userService from '@src/services/user';

import { isAuthenticated } from '@src/util/auth';
import type { Request, Response, RequestHandler } from 'express';
import express from 'express';

const router = express.Router();

/* ----------------------------------页面渲染 ---------------------------------- */
router.get("/", isAuthenticated, (async (req: Request, res: Response) => {

  const allposts = await getPosts();
  const categories = await getCategories();

  const postArr = Array.isArray(allposts) ? allposts : [allposts];

  const posts = postArr.map((post) => {
    return {
      ...post,
      category_title: categories.find((category) => category.id === post.categoryId)?.title
    }
  })

  return res.render("index", {
    posts,
    username: req.user?.username || '-'
  });
}) as RequestHandler)


router.get("/users/login", ((req, res) => {
  return res.render("login", {
    title: "Login"
  });
}) as RequestHandler)

router.get("/users/register", ((req, res) => {
  return res.render("register", {
    title: "Register"
  });
}) as RequestHandler)

/* ---------------------------------- post文章视图 ---------------------------------- */
router.get('/posts/show/:id', (async function (req, res, next) {
  const post = await getPosts({ id: Number(req.params.id) }) as PostType;
  const allcomment = await getComments({ postId: Number(req.params.id) });
  const categories = await getCategories();
  const users = await userService.getAllUser();

  const comments = allcomment.map(_ => ({
    ..._,
    username: users.find((user: User) => user.id === _.ownerId)?.name
  }))


  return res.render("showpost", {
    title: "Show",
    post: {
      userId: req.user?.id,
      ...post,
      category_title: categories.find((category) => category.id === post.categoryId)?.title,
      comments,
    }

  });
}) as RequestHandler)

router.get('/posts/edit/:id', (async function (req, res, next) {
  const post = await getPosts({ id: Number(req.params.id) }) as PostType;
  const categories = await getCategories();

  return res.render('editpost', {
    "title": post.title,
    "post": post,
    "categories": categories
  });
}) as RequestHandler)

router.get('/posts/add', (async function (req, res, next) {
  const categories = await getCategories();
  return res.render('addpost', {
    "title": "Add Post",
    "categories": categories
  });
}) as RequestHandler);

/* ---------------------------------- 评论视图 ---------------------------------- */



/* ---------------------------------- 分组视图 ---------------------------------- */
router.get('/categories/add', (function (req, res, next) {
  return res.render('addcategory', {
    title: "Add Category"
  });
}) as RequestHandler);


export default router;
